//
//
//
//
//
// StrUtil.C
// 2011/08/30 @CieNET

#include "StrUtil.h"
#include <iostream>
#include "Exception.h"

namespace Util
{
	static int _convert[10][10] = 
	{
		{0, 00, 000, 0000, 00000, 000000, 0000000, 00000000, 000000000, 0000000000},
		{1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000},
		{2, 20, 200, 2000, 20000, 200000, 2000000, 20000000, 200000000, 2000000000},
		{3, 30, 300, 3000, 30000, 300000, 3000000, 30000000, 300000000, 3000000000},
		{4, 40, 400, 4000, 40000, 400000, 4000000, 40000000, 400000000, 4000000000},
		{5, 50, 500, 5000, 50000, 500000, 5000000, 50000000, 500000000, 5000000000},
		{6, 60, 600, 6000, 60000, 600000, 6000000, 60000000, 600000000, 6000000000},
		{7, 70, 700, 7000, 70000, 700000, 7000000, 70000000, 700000000, 7000000000},
		{8, 80, 800, 8000, 80000, 800000, 8000000, 80000000, 800000000, 8000000000},
		{9, 90, 900, 9000, 90000, 900000, 9000000, 90000000, 900000000, 9000000000},
	};

	//
	// trim left
	std::string& TrimLeft(std::string& str)
	{
		std::string::iterator it = str.begin();
		for(;(*it == ' ' || *it == '\t' || *it == '\r'
					|| *it == '\n')&& it != str.end(); it++){}
		if(it != str.begin())
			str.erase(str.begin(), it);
		return str;
	}

	//
	// trim right
	std::string& TrimRight(std::string& str)
	{
		if(str.empty())
			return str;

		std::string::iterator it = str.end();
		it--;
		for(; (*it == ' ' || *it == '\t' || *it == '\r' 
					|| *it == '\n' )&& it != str.begin(); it--){}
		it++;
		str.erase(it, str.end());
		return str;
	}

	//
	//
	// trim both left & right
	//
	std::string& Trim(std::string& str)
	{
		TrimLeft(str);
		TrimRight(str);
		return str;
	}

	// convert string to 
	// of 32 plateform, the string int should not be larger than 2147483647
	//
	int StrConvert(const std::string& str)
	{
		if(str.empty())
			throw Exception("Convert failed, empty string input");

		std::string _tmp = str;
		Util::Trim(_tmp);

		std::string::reverse_iterator r_it = _tmp.rbegin();
		int nRet = 0;
		for(int nPos = 0; r_it != _tmp.rend(); r_it++)
		{
			if(*r_it != '.')
			{
				if(int(*r_it) < 0x30 || int(*r_it) > 0x39)
					throw Exception("Convert failed, invalide char found");

				nRet += _convert[int(*r_it) - 0x30][nPos];
				nPos++;
			}
			else
			{
				nRet = 0;
				nPos = 0;
			}
		}
		return nRet;
	}
};
